package com.sudo.interceptor;

import com.sudo.aspect.AuthorizationApi;
import com.sudo.common.enums.UserParams;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.RedisOperator;
import com.sudo.common.utils.RetResponse;
import com.sudo.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author：为道日损 2020-05-06 23:55
 * webSite：https://www.sudo.ren
 */
public class AuthorizationInterceptor extends BaseService implements HandlerInterceptor {
    @Autowired
    private RedisOperator redisOperator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = request.getHeader(UserParams.HEADER_USER_ID.value);

        String roleCode = getRoleCodeFromRedisByUsername(username);
        if (StringUtils.isBlank(roleCode)) {
            RetResponse.res(response, JsonRes.errorMsg("暂无权限"));
            return false;
        }
        String menuCode = null;
        String buttonCode = null;
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            AuthorizationApi authorizationApi = method.getMethodAnnotation(AuthorizationApi.class);
            assert authorizationApi != null;
            menuCode = authorizationApi.menu();
            buttonCode = authorizationApi.button();
        }
        //判断是否有按钮权限
        String key = UserParams.REDIS_ROLE_PERMISSION.value + ":" + roleCode + ":" + menuCode;
        boolean flag = redisOperator.sismember(key,buttonCode);
        if (flag) {
            return true;
        }
        RetResponse.res(response,JsonRes.errorMsg("暂无权限"));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
